import cv2

img = cv2.imread("../images/sum.png")

img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# img_gray = cv2.GaussianBlur(img_gray, (1,1), 0, 0)

ret, img_bin = cv2.threshold(img_gray, 100, 255,cv2.THRESH_BINARY)  #小于阈值的将转为纯黑色
img_canny = cv2.Canny(img_bin, 0, 1, 1)

# cv2.imwrite("binary.png", img_bin)
# cv2.namedWindow("bin", cv2.WINDOW_AUTOSIZE)
# cv2.namedWindow("canny", cv2.WINDOW_AUTOSIZE)
cv2.imshow("bin", img_bin)
cv2.imshow("canny", img_canny)

# contours, hierarchy = cv2.findContours(
#     img_bin, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

_, contours, hierarchy = cv2.findContours(img_canny, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

cv2.drawContours(img, contours, -1, (255, 0, 255), 1)  #最右边的参数是线粗细
cv2.imshow("result", img)

# print(contours)
# for i in contours:

#     for j in i:
#         print(j)
#         print("-----------")

with open("./path.txt", 'w') as f:
    f.write("pathArr[]=[")
    for i in contours:
        for j in i:
            f.write(str(j[0][0]))
            f.write(",")
            f.write(str(j[0][1]))
            f.write(",")

    f.write("];")

cv2.waitKey(5000)==27
cv2.destroyAllWindows()

